<?php
namespace Home\Controller;

use Vendor\Page;

class NovelController extends ComController{

    public function _initialize()
    {
        parent::_initialize();
    }


	
	/**
	 * 无刷新获得相对类型的小说列表
	 * */
	public function ajaxGetNovelList($class_id = 0, $other_class_id = 0, $start = 0, $limit = 10, $is_order = 0){
		if(!empty($class_id)){ //普通类型
			$map["class_id"] = $class_id;
		}
		
		if(!empty($other_class_id)){ //特别类型
			$map["other_class_id"] = $other_class_id;
		}
		
		$order_set = "id asc"; //热度排序
		if(!empty($is_order)){
			$order_set = "click_count desc";
		}
		
		//只显示上架的小说
		$map["is_shelf"] = 1;
		
		$list = D("Novel")->field("id,name as title,description as summary,img as avatar")->order($order_set)->where($map)->limit($start.",".$limit)->select();
		foreach($list as $key=>$item){
			$list[$key]["summary"] = mb_substr($item["summary"],1,70, "UTF-8");
		}
		
		$this->ajaxReturn($list);
	}
	
	/**
	 * 获取免费小说
	 * */
	public function ajaxGetFreeNovelList(){
		//获得最新的限时免费活动
		$activity = D("activity")->field("id,start_time,end_time")->where("status = 1 and type=1")->order("id desc")->find();
		$activity_id = $activity["id"];
		
		if(!empty($activity_id)) {
			//获得限免的小说
			$list= D("novel")->field("id,name as title,description as summary,img as avatar")->where("activity_id = $activity_id")->limit($start.",".$limit)->select();
			foreach($list as $key=>$item) {
				$list[$key]["is_free"] = 1;
				$list[$key]["start_time"] = $activity["start_time"];
				$list[$key]["end_time"] = $activity["end_time"];
				$list[$key]["summary"] = mb_substr($list[$key]["summary"], 0,80,"utf-8")."...";
			}
		}
		else
			$list = array();
		
		$this->ajaxReturn($list);
	}	
	
	/**
	 * 显示分类列表
	 * */
	public function getNovelList(){
        $this->is_session();
		$class_id = $_GET["class_id"] ? $_GET["class_id"] : 0;
		$this->assign("class_id", $class_id);
		
		$other_class_id= $_GET["other_class_id"] ? $_GET["other_class_id"] : 0;
		$this->assign("other_class_id", $other_class_id);
		
		$is_order= $_GET["is_order"] ? $_GET["is_order"] : 0;
		$this->assign("is_order", $is_order);
		
		//echo $other_class_id;
		
		if($other_class_id == 3)
			$this->assign("title", "男生");
		elseif($other_class_id == 4)
			$this->assign("title", "女生");
		else
			$this->assign("title", "排行");
		
		if($is_order == 5) {
			$this->assign("title", "限免");
			$this->assign("is_free", 1);
		}
		
		$this->display();
	}
	
	/**
	 * 获得所有类型
	 * */
	public function getClassList(){
        $this->is_session();
		$class_list = D("novel_class")->where("is_other = 0")->select();
		$this->assign("class_list",$class_list);
		$this->display();
	}
	
	/**
	 * 书库
	 * */
	public function ajaxGetClassList(){

		if(!empty($_GET["other_class_id"]))
			$map["other_class_id"] = $_GET["other_class_id"];
		if(!empty($_GET["class_id"]))
			$map["class_id"] = $_GET["class_id"];
		if($_GET["is_end"] == "0" || $_GET["is_end"] == 1)
			$map["is_end"] = $_GET["is_end"];
		
		$start = $_GET["start"];
		$limit = $_GET["limit"];
			
		
		$novel_list = D("novel")->field("id,name as title,img as avatar,description as summary")->where($map)->limit("$start,$limit")->select();
		$total = D("novel")->where($map)->count();
		$novel_list = ["data"=>$novel_list,"total"=>$total];
		
		//echo D("novel")->getLastSql();die;
		
		
		$this->ajaxReturn($novel_list);
	}	
	
	/**
	 * 搜索页面
	 * */
	public function search(){
		//热门搜索
        $key = $_GET['q'];
		//点击率最高的小说7本
		$hot_search = D("Novel")->field("id,name")->order("click_count desc")->where("is_shelf = 1")->limit("0,7")->select();
		$this->assign("hot_search", $hot_search);
		//精彩推荐
		//付费最高的10本小说
		//缓存中
		$wonderful = S("wonderful");
		if(empty($wonderful)) {
			$wonderful = D()->query("select a.*,b.description,b.img from (select (count(*) * 0.14) as money,novel_id,novel_name from qw_user_buy GROUP BY novel_id)a left join qw_novel as b on a.novel_id = b.id where b.is_shelf = 1 order by money desc limit 0,10");
			S("wonderful", $wonderful, 86400);
		}
		$this->assign("wonderful", $wonderful);
        $this->assign("key", $key);

        $this->display('search1');
	}
	


	
	/**
	 * 小说介绍
	 * */
	public function novelinfo($id = 0){
//        $this->is_session();

		$novel = D("novel")->where("id=".$id)->find();
//		echo D("novel")->getLastSql();
//		echo "<br/>";
//		die();
//		dump($novel);die;
		$this->assign("novel",$novel);
		
		 //查询当前用户所看小说是否有历史记录
        $openid = $_SESSION['user']['open_id'] ? $_SESSION['user']['open_id'] : $_SESSION['open_id'];
		$map['open_id'] = $openid;
		$map['novel_id'] = $id;
		$map['is_recommend'] = array("in",'1,2');
		$novel_isset = D('bookshelf')->where($map)->find();
		$this->assign('novel_isset',$novel_isset);

        $novelid = $novel["id"];

        if( empty($openid) ){
//        echo $novelid;
//        die();
            $curl_ready = D('read_history')->field('chapter_id')->where("novel_id = $novelid")->find();
//            echo D('read_history')->getLastSql();
//            die();
        }else{
            $curl_ready = D('read_history')->field('chapter_id')->where("novel_id = $novelid and open_id = '$openid'")->find();
//            echo D('read_history')->getLastSql();
//                        die();
        }


        if(!empty($curl_ready)){
            $this->assign("chapter_id",$curl_ready["chapter_id"]);
        }else{
            //第一章节ID
            $chapter = D("novel_chapter")->where("novel_id=".$novel["id"])->order("order_set asc")->find();
            $this->assign("chapter_id",$chapter["id"]);
        }
        $chapter_last = D("novel_chapter")->field('chapter,title,add_time')->where("novel_id=".$novel["id"])->order("order_set desc")->find();
        $time_arr = explode(' ',$chapter_last['add_time']);

        $this->assign('chapter_list',$chapter_last);
        $this->assign('time',$time_arr[0]);
        //dump($chapter_last);die;
		
//		//获得前4章的目录
//		$pre_chapter_list = D("novel_chapter")->where("novel_id=".$novel["id"])->order("order_set asc")->limit("0,4")->select();
//		$this->assign("pre_chapter_list",$pre_chapter_list);
		
		//查寻打赏总金额
        $domin = $_SERVER['HTTP_HOST'];
		$novel_id = $_GET['id'];
		$data = D('dashang_history')->query("select sum(das_money) as sum from qw_dashang_history where novel_id=$novel_id and domin='$domin'");
		//打赏的总金额
        $total_money = $data[0]['sum'];
		
        //推荐其它作品
        $novel_list = D('novel')->field('img,name,id')->order('click_count desc')->limit(3)->select();
        $this->assign('novel_list',$novel_list);
		
        $this->assign('data',$data);
        $this->assign('total_money',$total_money);
		//$this->assign("pre_chapter_list",$pre_chapter_list);
		
		$this->display('novelinfo1');
	}
	
	
	
	public function changeC(){
		$rows = D('novel')->where('is_shelf = 1')->order('rand()')->limit(3)->select();
        $file_host = C('FILE_HOST_PATH');
        $data = [];
        foreach ($rows as $key => $item){
            $data[$key] .= '<li><a href='."\"/Home/Novel/novelinfo/id/".$item['id']."\"><img src=\"$file_host".$item['img']."\"><p>".$item['name']."</p></a></li>";
        }
		$str  = implode('',$data);
		$arr['data'] = $str;
		//dump($item);
		
        $arr['status'] = 1;
        $arr['info'] = '成功';
	
        $this->ajaxReturn($arr);
		
	}
	
	
	
	/**
	 * 小说目录
	 * */
	public function novelcatalog($id = 0){
        $this->is_session();
		$novel = D("novel")->where("id = ".$id)->find();
		$chapter_count = D('novel_chapter')->where("novel_id = $id")->count();
		//dump($chapter_count);die;

		$this->assign("novel",$novel);
		$this->assign("chapter_count",$chapter_count);
		$this->display('mulv');
	}
	
	/**
	 * 无刷新获得小说的列表
	 * */
	public function ajaxcatalogList($id = 0, $start = 0){
		//$list = D("novel_chapter")->field("distinct id,chapter,title,novel_id,order_set")->order("order_set asc")->where("novel_id=".$id)->limit($start.", 20")->select();
		$start ++;
		$list = D()->query("SELECT distinct id,chapter,title,order_set FROM `qw_novel_chapter` where novel_id = ".$id." and order_set >= ".$start." and order_set <= ".($start+19));
		$free_chapter_arr = D('novel')->field('free_chapter')->where("id='$id'")->find();
        $free_chapter = $free_chapter_arr['free_chapter'];
		foreach($list as $key=>$item){
			if(intval($item["order_set"]) <= $free_chapter)
				$list[$key]["welth"] = 0;
			else
				$list[$key]["welth"] = 23;
		}
		$this->ajaxReturn($list);
	}
	
	/**
	 * 小说显示
	 * */
	public function show($id = 0, $novel_id = 0){
        $this->is_session();

		header("Content-type: text/html; charset=utf-8");

		//修复小说ID为空的时候
		//后期再去排查错误
		if(empty($novel_id)){
			//print_r($_GET);
			die("<meta charset='utf-8'>错误路径");
		}		
		
		//如果没有传章节ID
		if(empty($id)){
			$id = 0;
			$map['novel_id'] = $novel_id;
			$map['open_id'] = $_SESSION['user']['open_id'];
			$rs = D('read_history')->where($map)->find();
			if(!empty($rs['chapter_id']))
				$id = $rs['chapter_id'];
			else{
				$chapter_rs = D('novel_chapter')->where("novel_id = $novel_id")->find();
//				echo D('novel_chapter')->getLastSql();
//				die();
				$id = $chapter_rs['id'];
			}
		}
		
		$chapter = array();
//		echo $id;die();
		$chapter = D('novel_chapter')->where("novel_id = ".$novel_id)->limit('0,2')->select();

		$chapter[0]['content'] = trim($chapter[0]['content'], ' \t');
		$chapter[0]['content'] = trim($chapter[0]['content'], ' \n');
		$chapter[0]['content'] = trim($chapter[0]['content'], ' \0');
		$chapter[0]['content'] = trim($chapter[0]['content'], ' \r');
		$this->assign('chapter',$chapter);
//		print_r($chapter);
//        		die();
//		$this->assign('novel_img',C('FILE_HOST_PATH').$chapter[0]['novel_mini_img']);
		$this->assign('novel_img',$chapter[0]['novel_mini_img']);
//				print_r($chapter[0]['novel_mini_img']);
//                		die();
		
		//判断你小说是否下架
		$novel_info = D('novel')->where('id = '.$chapter[0]['novel_id'])->find();
		if(empty($novel_info['is_shelf'])) {
			echo "<meta charset='UTF-8'>";
			die("小说下架校对中");
		}
		
		$this->assign('novel_id', $novel_id);
		$this->assign('novel_name', $chapter[0]['novel_name']);
		if(empty($id)) {
			$this->assign('init_chapter_id', $chapter[0]['id']);
		}
		else 
			$this->assign('init_chapter_id', $id);
			
		//判断是否是免费小说
		//获取免费的活动，活动类型为1限时免费活动
		$activity = D('activity')->field('id,end_time')->where('status = 1 and type=1')->order('id desc')->find();
    	$activity_id = $activity['id'];
		$is_free = 0;
		if(!empty($activity_id)) {
			if($novel_info['activity_id'] == $activity_id)
				$is_free = 1;
		}		
		
		//判断是否是vip用户
		$is_vip = 0;
		$vip_rs = D('user')->field('is_vip')->where("open_id = '".$_SESSION["user"]["open_id"]."'")->find();
		$is_vip = $vip_rs['is_vip'];
//		$vip_data["test"] = $is_vip." ".$_SESSION["user"]["open_id"]." ".$_SESSION["user"]["nickname"];
//		D("test")->add($vip_data);
			
		//判断是否是付费章节		
		if(intval($chapter[0]['order_set']) > 20 && $is_free == 0 && $is_vip == 0){
			
			//判断是否已经付过钱了
			$buy_map['open_id'] = $_SESSION['user']['open_id'];
			$buy_map['chapter_id'] = $chapter[0]['id'];
			$buy_map['novel_id'] = $chapter[0]['novel_id'];
			$user_buy = D('user_buy')->where($buy_map)->find();
			if(count($user_buy) == 0) {
				//die($chapter[0]["order_set"]);
				//判断用户的书币是否足够
				//一章节需要$pay_money书币					
				$pay_money = chapter_money($chapter[0]['word_count']);
				$user = D('user')->where("open_id='".$_SESSION["user"]["open_id"]."'")->find();
				if(intval($user['book_money']) < $pay_money)  { //钱不够去充值
					header('Location: http://'.$_SERVER['HTTP_HOST'].'/Home/User/recharge.html?book_money='.$user['book_money'].'&chapter_money='.$pay_money);
					die;
				}
				else{ //钱足够
					//事务处理
					M()->startTrans();
				
					//自动扣费
					$money_map['open_id'] = $_SESSION['user']['open_id'];
					$m_data['book_money'] = array('exp', "book_money-$pay_money");
					$m_state = M('user')->where($money_map)->save($m_data);
					//D()->execute("update qw_user set book_money=book_money-14 where open_id='".$_SESSION["user"]["open_id"]."'");
					
					//if(!empty($chapter[0]["novel_name"]) && !empty($chapter[0]["title"])) {
						//添加本章节已经是用户付费的章节，以后都可以观看了
						$buy_data['open_id'] = $_SESSION['user']['open_id'];
						$buy_data['novel_id'] = $chapter[0]['novel_id'];
						$buy_data['novel_name'] = $chapter[0]['novel_name'];
						$buy_data['chapter_id'] = $chapter[0]['id'];
						$buy_data['chapter_name'] = $chapter[0]['title'];
						$buy_data['chapter'] = $chapter[0]['chapter'];
						$buy_data['buy_time'] = date('Y-m-d H:i:s');
						$buy_data['pay_money'] = $pay_money;
						$buy_state = M('user_buy')->add($buy_data);
					//}
					
					if(empty($buy_state) || empty($m_state)) {
						M()->rollback();
						die('交易错误');
					}
					else
						M()->commit();
				}
			}
		}
	
		//增加小说的点击量
		//echo $novel_id;die;
//		if(!empty($novel_id)){
//			D()->execute('update qw_novel set click_count=click_count+1 where id='.$novel_id);
//		}


		
		//增加用户的浏览记录
		if(!empty($_SESSION['user'])){
			$map['open_id'] = $_SESSION['user']['open_id'];
			$map['novel_id'] = $novel_id;
			//$map["chapter_id"] = $id;
			//print_r($_SESSION["user"]);die;
			$history_count = D('read_history')->where($map)->find();
			if(count($history_count) == 0){
				//if(!empty($novel["name"]) && !empty($chapter[0]["title"])) {
					$novel = D('novel')->where("id=$novel_id")->find();
					$data['open_id'] = $_SESSION['user']['open_id'];
					$data['novel_id'] = $novel_id;
					$data['novel_name'] = $novel['name'];
					$data['chapter_id'] = $chapter[0]['id'];
					$data['chapter_name'] = $chapter[0]['title'];
					$data['chapter'] = $chapter[0]['chapter'];
					$data['addtime'] = date('Y-m-d H:i:s');
					//print_r($data);die;
					//if(!empty($data['novel_id']) && !empty($data['chapter_id']))
						D('read_history')->add($data);
				//}
			}
			else{
				$map['history_id'] = $history_count['history_id'];
				$data['chapter_id'] = $chapter[0]['id'];;
				$data['chapter_name'] = $chapter[0]['title'];
				$data['chapter'] = $chapter[0]['chapter'];
				$data['addtime'] = date('Y-m-d H:i:s');
				//if(!empty($data['novel_id']) && !empty($data['chapter_id']))
					D('read_history')->where($map)->save($data);
			}
			
		}
		$this->assign('domain',$_SERVER['HTTP_HOST']);
		$this->assign('novel_id', $novel_id);
		
		//判断是否是第8章
		//如果是，且当前用户没有关注的时候就要他强行关注
		$is_show = 1;
		//查询这个用户是否关注我们平台
		$user_info = D('user')->where("open_id='".$_SESSION["user"]["open_id"]."'")->find();
		//查询对应用户所
		if(intval($chapter[0]['order_set']) >= 8){
			if(empty($user_info['subscribe']))
				$is_show = 0;
			else
				$is_show = 1;
		}
		else{
			$is_show = 1;
		}
		$this->assign('is_show',$is_show);
		
		//是显示签到
		//判断今天是否签到
		$qiandao = D('qiandao')->where("open_id='".$_SESSION["user"]["open_id"]."' and qd_date='".date("Y-m-d")."'")->find();
		if(empty($qiandao)){				
			//添加书币
			$money_data['book_money'] = array('exp', "book_money+20");
			$user_state = D('user')->where("open_id='".$_SESSION["user"]["open_id"]."'")->save($money_data);
			//添加签到信息
			$qiandao_data['open_id'] = $_SESSION['user']['open_id'];
			$qiandao_data['qd_date'] = date('Y-m-d');
			$qiandao_data['nickname'] = $_SESSION['user']['nickname'];
			D('qiandao')->add($qiandao_data);
			$this->assign('sign',1);
		}


		$rs = D("platform")->where(["domain"=>$_SESSION["user"]["domain"]])->find();
		$this->assign("tongji",$rs["tongji_id"]);		

		$this->display('show_new_pwd');

	}
	
	/**
	 * ajax获得小说章节
	 * */
	public function ajaxgetchapter(){
        $this->is_session();

	
		if(empty($_GET["novel_id"])){
			echo "bad link";
			die;
		}
		
		$list = array();
		$c_rs = array();
		if(!empty($_GET["chapter_id"])) {
			$map["novel_id"] = $_GET["novel_id"];
			$map["id"] = $_GET["chapter_id"];
			$list = D("novel_chapter")->where($map)->find();
		}
		else{
			//获得最前一章节
			$map["novel_id"] = $_GET["novel_id"];
			$c_rs = D("novel_chapter")->where($map)->order("id asc")->find();
			$map["id"] = $c_rs["id"];
			$list = D("novel_chapter")->where($map)->find();
		}
		
		//获得下一个章节的ID
		$nmap["novel_id"] = $_GET["novel_id"];
		$chapter_id = $_GET["chapter_id"] ? $_GET["chapter_id"] : $c_rs["id"];
		$nmap["id"] = array("gt", $chapter_id);
		$next = D("novel_chapter")->where($nmap)->find();
		
		//获得上一章节的ID
		$nmap["novel_id"] = $_GET["novel_id"];
		$chapter_id = $_GET["chapter_id"] ? $_GET["chapter_id"] : $c_rs["id"];
		$nmap["id"] = array("lt", $chapter_id);
		$pre = D("novel_chapter")->order("id desc")->where($nmap)->find();
		
		$data["chapter_id"] = $_GET["chapter_id"] ? $_GET["chapter_id"] : $c_rs["id"];
		$data["novel_id"] = $_GET["novel_id"];
		$data["title"] = $list["chapter"]." ".$list["title"];
		$data["content"] = $list["content"];
		$data["next_chapter_id"] = $next["id"];
		$data["pre_chapter_id"] = $pre["id"];
		$data["order_set"] = $list["order_set"];
		$data["result"] = "1";
		$chapter = D("novel_chapter")->where("id = ".$chapter_id)->order("id asc")->limit(2)->select();
		//图片
		$this->assign("novel_img",$chapter[0]["novel_mini_img"]);
		
		//增加小说的点击量
		//echo $novel_id;die;
		if(!empty($_GET["novel_id"])){
			D()->execute("update qw_novel set click_count=click_count+1 where id=".$_GET["novel_id"]);
		}
		
		//判断是否是免费小说
		//获取免费的活动，活动类型为1限时免费活动
		$novel_info = D("novel")->where("id = ".$chapter[0]["novel_id"])->find();
		$pay_chapter = $novel_info['free_chapter'];
		$activity = D("activity")->field("id,end_time")->where("status = 1 and type=1")->order("id desc")->find();
    	$activity_id = $activity["id"];
		$is_free = 0;
		if(!empty($activity_id)) {
			if($novel_info["activity_id"] == $activity_id)
				$is_free = 1;
		}
		
		//判断是否是vip用户
		$is_vip = 0;
		$vip_rs = D("user")->field("is_vip")->where("open_id = '".$_SESSION["user"]["open_id"]."'")->find();
		$is_vip = $vip_rs["is_vip"];		
		
		if(intval($chapter[0]["order_set"]) > $pay_chapter && $is_free == 0 && $is_vip == 0){			
			//判断是否已经付过钱了
			$buy_map["open_id"] = $_SESSION["user"]["open_id"];
			$buy_map["chapter_id"] = $chapter[0]["id"];
			$buy_map["novel_id"] = $chapter[0]["novel_id"];			
			$user_buy = D("user_buy")->where($buy_map)->find();
			if(count($user_buy) == 0) {
				//die($chapter[0]["order_set"]);
				//判断用户的书币是否足够
				//一章节需要$pay_money书币					
				$pay_money = chapter_money($chapter[0]["word_count"]);			
				$user = D("user")->where("open_id='".$_SESSION["user"]["open_id"]."'")->find();
				if(intval($user["book_money"]) < $pay_money)  { //钱不够去充值 
					//header("Location: http://".$_SERVER['HTTP_HOST']."/Home/User/recharge.html?book_money=".$user["book_money"]);
					$data["content"] = "";
					$data["result"] = 0;
				}
				else{ //钱足够
					//事务处理
					M()->startTrans();
				
					//自动扣费
					$money_map["open_id"] = $_SESSION["user"]["open_id"];
					$m_data["book_money"] = array("exp", "book_money-$pay_money");
					$m_state = M("user")->where($money_map)->save($m_data);
					//D()->execute("update qw_user set book_money=book_money-14 where open_id='".$_SESSION["user"]["open_id"]."'");
					
					//if(!empty($chapter[0]["novel_name"]) && !empty($chapter[0]["title"])) {
						//添加本章节已经是用户付费的章节，以后都可以观看了
						$buy_data["open_id"] = $_SESSION["user"]["open_id"];
						$buy_data["novel_id"] = $chapter[0]["novel_id"];
						$buy_data["novel_name"] = $chapter[0]["novel_name"];
						$buy_data["chapter_id"] = $chapter[0]["id"];
						$buy_data["chapter_name"] = $chapter[0]["title"];
						$buy_data["chapter"] = $chapter[0]["chapter"];
						$buy_data["buy_time"] = date("Y-m-d H:i:s");
						$buy_data["pay_money"] = $pay_money;
						$buy_state = M("user_buy")->add($buy_data);	
					//}
					
					if(empty($buy_state) || empty($m_state)) {
						M()->rollback();
						die("交易错误");
					}
					else
						M()->commit();
				}
			}
		}

		
		if(!empty($data["result"])) {
			//增加用户的浏览记录
			if(!empty($_SESSION["user"])){
				$map["open_id"] = $_SESSION["user"]["open_id"];
				$map["novel_id"] = $_GET["novel_id"];
				//$map["chapter_id"] = $id;
				//print_r($_SESSION["user"]);die;
				$history_count = D("read_history")->where($map)->find();
				if(count($history_count) == 0){
					//if(!empty($novel["name"]) && !empty($chapter[0]["title"])) {
						$novel = D("novel")->where("id=".$_GET["novel_id"])->find();
						$data["open_id"] = $_SESSION["user"]["open_id"];
						$data["novel_id"] = $_GET["novel_id"];
						$data["novel_name"] = $novel["name"];
						$data["chapter_id"] = $chapter[0]["id"];
						$data["chapter_name"] = $chapter[0]["title"];
						$data["chapter"] = $chapter[0]["chapter"];
						$data["addtime"] = date("Y-m-d H:i:s");
						//print_r($data);die;
						D("read_history")->add($data);
					//}
				}
				else{
					$map["history_id"] = $history_count["history_id"];
					$data["chapter_id"] = $chapter[0]["id"];;
					$data["chapter_name"] = $chapter[0]["title"];
					$data["chapter"] = $chapter[0]["chapter"];
					$data["addtime"] = date("Y-m-d H:i:s");
					D("read_history")->where($map)->save($data);
				}				
			}		
		}
		
		$is_show = 0;
		//查询这个用户是否关注我们平台
		$user_info = D("user")->where("open_id='".$_SESSION["user"]["open_id"]."'")->find();
		//查询对应用户所
        $novel_id = $_GET["novel_id"];
        $subscribe_chapter_arr = D('novel')->field('subscribe_chapter')->where('id='.$novel_id)->find();
        $subscribe_chapter = $subscribe_chapter_arr['subscribe_chapter'];
        if(intval($chapter[0]["order_set"]) >= intval($subscribe_chapter)){
			if(empty($user_info["subscribe"]))
				$is_show = 1;
			else
				$is_show = 0;
		}
		else{
			$is_show = 0;
		}
		$data["is_show"] = $is_show;
        //传智能推荐的小说
        $open_id = $_SESSION['user']['open_id'];
        //var_dump($open_id);die;
        if(!empty($open_id)){
            $recommend_arr = json_decode(curl_request('http://bfvnu.cn/Home/api/returncache1/open_id/'.$open_id),true);
            if(empty($recommend_arr)){
                $recommend_arr = D('novel')->field('id,name,img,description')->where('id=890')->select();
            }
            //dump($recommend_arr);die;
            $data['workimg'] = C('FILE_HOST_PATH').$recommend_arr[0]['img'];
            $data['workname'] = $recommend_arr[0]['name'];
            $data['workcontent'] = $recommend_arr[0]['description'];
            $data['workurl'] = '/Home/Novel/novelinfo/id/'.$recommend_arr[0]['id'];
        }
        //var_dump($data);die;


		
		echo $this->ajaxReturn($data);
	}
	
	/**
	 * 获得小说目录
	 * */
	public function ajaxgetchapterlist(){
		$novel_id = $_GET["novel_id"];
		if(empty($novel_id)){
			echo "bad link";
			die;
		}
		
		$map["novel_id"] = $novel_id;
		//$list = D("novel_chapter")->field("id as chapter_id,chapter,title,order_set")->where($map)->select();
		$list = D()->query("SELECT distinct id as chapter_id,chapter,title,order_set FROM `qw_novel_chapter` where novel_id = ".$novel_id);
		
		echo $this->ajaxReturn($list);
	}	
	
	/**
	 * 浏览记录查看
	 */
	public function readhistory(){
        $this->is_session();

        $map["open_id"] = $_SESSION["user"]["open_id"];

        $history = D("read_history")->order("addtime desc")->limit("0,15")->where($map)->select();

        //print_r($history);die;
        $this->assign("history", $history);
        $this->assign("domain", $_SERVER["HTTP_HOST"]);
        $this->display();

	}
	
	/**
	 * 添加书签
	 * */
	public function addbooksign(){
        $this->is_session();
		if(!empty($_SESSION["user"])){
			$map["id"] = $_GET["chapter_id"];
			$chapter = D("novel_chapter")->where($map)->find();
			
			$map1["open_id"] = $_SESSION["user"]["open_id"];
			$map1["novel_id"] = $_GET["novel_id"];
			$map1["chapter_id"] = $_GET["chapter_id"];
			$sign = D("novel_sign")->where($map1)->find();

			
			
			if(count($sign) == 0){
				$data["open_id"] = $_SESSION["user"]["open_id"];
				$data["novel_id"] = $chapter["novel_id"];
				$data["novel_name"] = $chapter["novel_name"];
				$data["chapter_id"] = $chapter["id"];
				$data["chapter_name"] = $chapter["title"];
				$data["chapter"] = $chapter["chapter"];
				M("novel_sign")->add($data);
				echo "ok";
			}
		}
	}
	
	/**
	 * 显示书签没有分页
	 * */
	public function showsign(){
        $this->is_session();
        $map["open_id"] = $_SESSION["user"]["open_id"];
        $sign = D("novel_sign")->where($map)->select();
        $this->assign("sign", $sign);
        $this->display();


	}
	
	/**
	 * 删除标签
	 * */
	public function delsign(){
		if(!empty($_SESSION["user"])){
			if(!empty($_GET["sign_id"]))
				$map["sign_id"] = $_GET["sign_id"];
				D("novel_sign")->where($map)->delete();
				echo $this->ajaxReturn(array("message"=>"删除成功","status"=>1));
		}else{
			echo $this->ajaxReturn(array("message"=>"无效请求"));
		}
	}
	
	/**
     * 打赏功能
     */
	 public  function dashang(){
        $this->is_session();

	    $openid = $_SESSION['user']['open_id'];
	    $novel_id = $_POST['novel_id'];
	    $das_pic = $_POST['gift_id'];
	    if ($das_pic == 1){
	        $das_money = 100;
        }elseif($das_pic == 2){
            $das_money = 388;
        }elseif($das_pic == 3){
            $das_money = 588;
        }elseif($das_pic == 4){
            $das_money = 888;
        }
        //查出剩余的书币
        $book_moneys = D('user')->where("open_id='$openid'")->find();
        $book_money = $book_moneys['book_money'];
        $img = $_SESSION['user']['img'];
        $nickname = $_SESSION['user']['nickname'];
	
		//查出小说的名字信息
		$novel = D("novel")->field('name')->where("id=".$novel_id)->find();
        
        //判断书币是非足够
         if ($book_money >= $das_money){
             //用户剩余的书币
             $sy_money = $book_money-$das_money;
             D('user')->where("open_id='$openid'")->save(['book_money'=>$sy_money]);
             //查寻打赏总金额
			$domin = $_SERVER['HTTP_HOST'];
			$total_moneys = D('dashang_history')->query("select sum(das_money) as sum from qw_dashang_history where novel_id=$novel_id and domin='$domin'");
             $total_money = $total_moneys[0]['sum']+$das_money;
             //添加打赏记录
             $data['open_id']=$openid;
             $data['novel_name']=$novel['name'];
             $data['das_money']=$das_money;
			 $data['das_pic']=$das_pic;
             $data['time']=date('Y-m-d H:i:s',time());
			 $data['img']=$img;
			 $data['domin']=$domin;
			 $data['nickname']=$nickname;
			 $data['novel_id']=$novel_id;
             D('dashang_history')->data($data)->add();
             $arr['money'] = $total_money;
             $arr['img'] = $_SESSION['user']['img'];
             $arr['nickname'] = $_SESSION['user']['nickname'];
             $arr['time']=date('Y-m-d H:i:s',time());
             $arr['das_pic']=$das_pic;
             $arr['status'] = 200;
         }else{
             $arr['status'] = 201;

         }
         echo json_encode($arr);
     }
	 
	 //更多记录
	 public function loadmore(){
	     $this->is_session();
         $novel_id = $_GET['novel_id'];
	     $page = $_GET['page']-1;
	     $count = $page*5;
	     $data = D('dashang_history')->query("select * from qw_dashang_history where novel_id = $novel_id order by time desc limit $count,5");
         echo json_encode($data);

     }


     /**
      * 未完待续功能
      */
     public function novel_end($novel_id = ''){
         //dump($novel_id);die;
         //原来看的那本小说
         $novel_name = D('novel')->field('id,name,is_end')->where('id='.$novel_id)->find();


         //付费最高的小说
         //$novel_top1 = json_decode(curl_request('http://test50.double-life.top/Home/api/get_pay_top1'),true);
         $novel_top1 = D('novel')->field('id,name,is_end,mini_img')->where('id=136')->find();
         //dump($novel_top1);die;

         //随机付费最高的小说
         $pay_novel_rand_4 = json_decode(curl_request('http://test50.double-life.top/Home/api/get_pay_rand_4'),true);
         //dump($pay_novel_rand_4);die;
         //新书推荐
         $new_novel = D('novel')->field('id,name,img')->order('publish_time ')->limit(4)->select();

//         dump($novel_top1);die;
         //dump($new_novel);

//         dump($pay_novel_rand_4);die;
         $this->assign('new_novel',$new_novel);

         $this->assign('pay_novel_rand_4',$pay_novel_rand_4);
         $this->assign('novel_top1',$novel_top1);
         $this->assign('novel_name',$novel_name);
         $this->display();
     }
	
}